from django.shortcuts import render

from base.models import Post
from django.http import HttpResponse, HttpResponseRedirect


# 创建数据并返回id
def create(request):
    post = Post(name='技术经理')
    post.save()
    return HttpResponse('新增岗位信息,返回的id=' + str(post.id))


# 访问数据
def index(request):
    posts = Post.objects.all()
    # post_list = []
    # for post in posts:
    #     del_str = "<a href='delete/{0}/'>删除</a>\t|".format(post.id)
    #     update_str = "\t<a href='update/{0}/'>修改</a><br/>".format(post.id)
    #     post_list.append(str(post.id) + ' \t ' + post.name + '\t')
    #     post_list.append(del_str)
    #     post_list.append(update_str)
    # return HttpResponse(post_list)
    return render(request, 'base/index.html', {'posts': posts, 'counter': posts.count})


# 删除数据
def delete(request, post_id):
    try:
        Post.objects.filter(id=post_id).delete()
    except Post.DoesNotExist:
        return HttpResponse('你要修改的岗位信息不存在，请确认！')
    else:
        return HttpResponseRedirect('/base/')


# 修改数据
def update(request, post_id):
    try:
        post = Post.objects.get(id=post_id)
        post.name = '吹牛经理'
        post.save()
    except Post.DoesNotExist:
        return HttpResponse('你要修改的岗位信息不存在，请确认！')
    else:  # 无异常时else block执行
        return HttpResponseRedirect('/base/')
